package org.demo.job;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;

/**
 * @author yexi
 */
public class JobDemo {
    public static void main(String[] args) {
        // 启动主方法时加载任务信息
        new JobScheduler(
                // 注册中心信息。告诉 elasticJob 任务信息要放在哪里
                createRegistryCenter("localhost:2181", "elastic-job-demo"),
                // 任务配置。告诉 elasticJob 任务要在什么时候执行
                createJobConfiguration()
        ).init();
    }

    /**
     * 创建注册中心配置
     *
     * @param serverLists 连接Zookeeper服务器的地址列表，包括IP地址和端口号. 多个地址用逗号分隔。如: host1:2181,host2:2181
     * @param namespace   命名空间
     */
    private static CoordinatorRegistryCenter createRegistryCenter(String serverLists, String namespace) {
        //配置zk地址,调度任务的组名
        ZookeeperConfiguration zookeeperConfiguration = new ZookeeperConfiguration(serverLists, namespace);
        zookeeperConfiguration.setSessionTimeoutMilliseconds(100);
        CoordinatorRegistryCenter regCenter = new ZookeeperRegistryCenter(zookeeperConfiguration);
        regCenter.init();
        return regCenter;
    }

    /**
     * 创建作业配置
     */
    private static LiteJobConfiguration createJobConfiguration() {
        // 定义作业核心配置
        JobCoreConfiguration simpleCoreConfig = JobCoreConfiguration.newBuilder(
                // 任务名称
                "demoSimpleJob",
                // cron表达式
                "0/5 * * * * ?",
                // 分片数量
                1
        ).build();
        // 定义SIMPLE类型配置
        SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(
                simpleCoreConfig,
                MyElasticJob.class.getCanonicalName());
        // 定义Lite作业根配置
        LiteJobConfiguration simpleJobRootConfig = LiteJobConfiguration.newBuilder(simpleJobConfig).build();
        return simpleJobRootConfig;
    }
}